//
//  AlertTool.m
//  TeacherEdu2016
//
//  Created by ADIQueen on 16/12/7.
//  Copyright © 2016年 teacher of china. All rights reserved.
//

#import "AlertTool.h"
#import "MBProgressHUD.h"
//Toast默认停留时间
#define ToastDispalyDuration 1.2f
//Toast到顶端/底端默认距离
#define ToastSpace 100.0f
//Toast背景颜色
#define ToastBackgroundColor [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.75]
#define kKeyWindow [UIApplication sharedApplication].keyWind
#define kScreenWidth ([UIScreen mainScreen].bounds.size.width)
#define kScreenHeight ([[UIScreen mainScreen] bounds].size.height)

@interface  AlertTool()
{
    UIButton *_contentView;
    UILabel *_textLabel;
    CGFloat  _duration;
    MBProgressHUD *_progressHUD;
    UIView * bgview;
}
@end
@implementation AlertTool

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice]];
}

- (id)initWithText:(NSString *)text{
    if (self = [super init]) {
        
        UIFont *font = [UIFont boldSystemFontOfSize:16];
        NSDictionary * dict=[NSDictionary dictionaryWithObject: font forKey:NSFontAttributeName];
        CGRect rect=[text boundingRectWithSize:CGSizeMake(250,CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
        if (_textLabel == nil) {
            _textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0,rect.size.width + 40, rect.size.height+ 20)];
            _textLabel.backgroundColor = [UIColor clearColor];
            _textLabel.textColor =[UIColor  whiteColor];
            _textLabel.textAlignment = NSTextAlignmentCenter;
            _textLabel.font = font;
            _textLabel.numberOfLines = 0;
        }
        _textLabel.frame = CGRectMake(0, 0,rect.size.width + 40, rect.size.height+ 20);
        if (_contentView == nil) {
            _contentView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, _textLabel.frame.size.width, _textLabel.frame.size.height)];
            _contentView.layer.cornerRadius = 20.0f;
            _contentView.backgroundColor = ToastBackgroundColor;
            //            _contentView.backgroundColor = [UIColor redColor];
            [_contentView addSubview:_textLabel];
            _contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
            [_contentView addTarget:self action:@selector(toastTaped:) forControlEvents:UIControlEventTouchDown];
            _contentView.alpha = 0.0f;
        }
        if (bgview==nil){
            
        }
        _textLabel.text = text;
        _contentView.frame = CGRectMake(0, 0, _textLabel.frame.size.width, _textLabel.frame.size.height);
        _duration = ToastDispalyDuration;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChanged:) name:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice]];
    }
    return self;
}

- (void)deviceOrientationDidChanged:(NSNotification *)notify{
    [self hideAnimation];
}

-(void)dismissToast{
    [_contentView removeFromSuperview];
}

-(void)toastTaped:(UIButton *)sender{
    [self hideAnimation];
}

- (void)setDuration:(CGFloat)duration{
    _duration = duration;
}

-(void)showAnimation{
    [UIView beginAnimations:@"show" context:NULL];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:0.3];
    _contentView.alpha = 1.0f;
    [UIView commitAnimations];
}

-(void)hideAnimation{
    [UIView beginAnimations:@"hide" context:NULL];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(dismissToast)];
    [UIView setAnimationDuration:0.3];
//    bgview.alpha = 0.0f;
    _contentView.alpha=0.0f;
    [UIView commitAnimations];
}

- (void)show{
    UIWindow *window = [[[UIApplication sharedApplication] windows] lastObject];
    _contentView.center = window.center;
    [window  addSubview:_contentView];
    [self showAnimation];
    [self performSelector:@selector(hideAnimation) withObject:nil afterDelay:_duration];
}

- (void)showFromTopOffset:(CGFloat)top{
    UIWindow *window = [[[UIApplication sharedApplication] windows] lastObject];
    _contentView.center = CGPointMake(window.center.x, top + _contentView.frame.size.height/2);
    [window  addSubview:_contentView];
    [self showAnimation];
    [self performSelector:@selector(hideAnimation) withObject:nil afterDelay:_duration];
}

- (void)showFromBottomOffset:(CGFloat)bottom{
    UIWindow *window = [[[UIApplication sharedApplication] windows] lastObject];
    
//    bgview=[[UIView alloc]initWithFrame:window.bounds];
    bgview.backgroundColor =[UIColor clearColor];
    
    _contentView.center = CGPointMake(window.center.x, window.frame.size.height-(bottom + _contentView.frame.size.height/2));
//    [bgview  addSubview:_contentView];
    
    [window addSubview:_contentView];
    [self showAnimation];
    [self performSelector:@selector(hideAnimation) withObject:nil afterDelay:_duration];
}

#pragma mark-中间显示
+ (void)showCenterWithText:(NSString *)text{
    [AlertTool showCenterWithText:text duration:ToastDispalyDuration];
}

+ (void)showCenterWithText:(NSString *)text duration:(CGFloat)duration{
    AlertTool *toast = [[AlertTool alloc] initWithText:text];
    [toast setDuration:duration];
    [toast show];
}
#pragma mark-上方显示
+ (void)showTopWithText:(NSString *)text{
    
    [AlertTool showTopWithText:text  topOffset:ToastSpace duration:ToastDispalyDuration];
}
+ (void)showTopWithText:(NSString *)text duration:(CGFloat)duration
{
    [AlertTool showTopWithText:text  topOffset:ToastSpace duration:duration];
}
+ (void)showTopWithText:(NSString *)text topOffset:(CGFloat)topOffset{
    [AlertTool showTopWithText:text  topOffset:topOffset duration:ToastDispalyDuration];
}

+ (void)showTopWithText:(NSString *)text topOffset:(CGFloat)topOffset duration:(CGFloat)duration{
    AlertTool *toast = [[AlertTool alloc] initWithText:text];
    [toast setDuration:duration];
    [toast showFromTopOffset:topOffset];
}
#pragma mark-下方显示
+ (void)showBottomWithText:(NSString *)text{
    
    [AlertTool showBottomWithText:text  bottomOffset:ToastSpace duration:ToastDispalyDuration];
}
+ (void)showBottomWithText:(NSString *)text duration:(CGFloat)duration
{
    [AlertTool showBottomWithText:text  bottomOffset:ToastSpace duration:duration];
}
+ (void)showBottomWithText:(NSString *)text bottomOffset:(CGFloat)bottomOffset{
    [AlertTool showBottomWithText:text  bottomOffset:bottomOffset duration:ToastDispalyDuration];
}

+ (void)showBottomWithText:(NSString *)text bottomOffset:(CGFloat)bottomOffset duration:(CGFloat)duration{
    AlertTool *toast = [[AlertTool alloc] initWithText:text];
    [toast setDuration:duration];
    [toast showFromBottomOffset:bottomOffset];
}



- (void)initMBProgressHUD:(NSString *)str inView:(UIView *)view
{
    if (_progressHUD == nil) {
        _progressHUD = [[MBProgressHUD alloc] initWithView:view];
        _progressHUD.frame = CGRectMake(view.frame.size.width/2 - 50, 100, 100, 100);
        _progressHUD.label.font = [UIFont systemFontOfSize:14.0];
        _progressHUD.mode = MBProgressHUDModeText;
        _progressHUD.minSize = CGSizeMake(100, 50);
    }
    [view addSubview:_progressHUD];
    _progressHUD.label.text = str;
    [_progressHUD showAnimated:YES];//开始显示
    [self performSelector:@selector(_progressHUDDisAppear) withObject:nil afterDelay:1.0];
}
- (void)_progressHUDDisAppear
{
    [_progressHUD hideAnimated:YES];
}

-(void)showAlertWithOneButtonTitle:(NSString *)title message:(NSString *)message preferredStyle:(UIAlertControllerStyle)preferredStyle inViewController:(UIViewController *)viewcontroller  deteminClicked:(DeteminClicked)deteminClicked{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:preferredStyle];
    UIAlertAction *detemin = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        deteminClicked();
    }];
    if (preferredStyle == UIAlertControllerStyleActionSheet) {
        alert.popoverPresentationController.sourceRect=CGRectMake(0, 0, kScreenWidth, kScreenHeight-200);
        alert.popoverPresentationController.sourceView=viewcontroller.view;
    }
    [alert addAction:detemin];
    [viewcontroller presentViewController:alert animated:YES completion:nil];
}
/**
 取消和删除选项弹窗
 */
-(void)showAlertWithTitle:(NSString *)title message:(NSString *)message preferredStyle:(UIAlertControllerStyle)preferredStyle inViewController:(UIViewController *)viewcontroller cancelClicked:(CancelClicked)cancelClicked deteminClicked:(DeteminClicked)deteminClicked{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:preferredStyle];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        cancelClicked();
    }];
    UIAlertAction *detemin = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        deteminClicked();
    }];
    if (preferredStyle == UIAlertControllerStyleActionSheet) {
        alert.popoverPresentationController.sourceRect=CGRectMake(0, 0, kScreenWidth, kScreenHeight-200);
        alert.popoverPresentationController.sourceView=viewcontroller.view;
    }
    [alert addAction:cancel];
    [alert addAction:detemin];
    [viewcontroller presentViewController:alert animated:YES completion:nil];
}
-(void)showAlertWithTitle:(NSString *)title subTitleOne:(NSString *)subTitleOne subTitleTwo:(NSString *)subTitleTwo message:(NSString *)message preferredStyle:(UIAlertControllerStyle)preferredStyle inViewController:(UIViewController *)viewcontroller cancelClicked:(CancelClicked)cancelClicked deteminClicked:(DeteminClicked)deteminClicked{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:preferredStyle];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:subTitleOne style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        cancelClicked();
    }];
    UIAlertAction *detemin = [UIAlertAction actionWithTitle:subTitleTwo style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        deteminClicked();
    }];
    if (preferredStyle == UIAlertControllerStyleActionSheet) {
        alert.popoverPresentationController.sourceRect=CGRectMake(0, 0, kScreenWidth, kScreenHeight-200);
        alert.popoverPresentationController.sourceView=viewcontroller.view;
    }
    
    [alert addAction:cancel];
    [alert addAction:detemin];
    [viewcontroller presentViewController:alert animated:YES completion:nil];
}

-(void)showAndDissmissAlertWithTitle:(NSString *)title message:(NSString *)message preferredStyle:(UIAlertControllerStyle)preferredStyle inViewController:(UIViewController *)viewcontroller{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:preferredStyle];
    if (preferredStyle == UIAlertControllerStyleActionSheet) {
        alert.popoverPresentationController.sourceRect=CGRectMake(0, 0, kScreenWidth, kScreenHeight-200);
        alert.popoverPresentationController.sourceView=viewcontroller.view;
    }
    [viewcontroller presentViewController:alert animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert dismissViewControllerAnimated:YES completion:nil];
    });
}
+(void)showAlertView:(UIViewController *)viewController title:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitle:(NSString *)otherButtonTitle cancleHandler:(void (^)())cancle otherHandler:(void (^)())confirm{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    // Create the actions.
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        cancle();
    }];
    
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        confirm();
    }];
    
    // Add the actions.
    [alertController addAction:cancelAction];
    [alertController addAction:otherAction];
    
    [viewController presentViewController:alertController animated:YES completion:nil];
}

/**
 底部弹窗 除取消之外有两个选项
 */
-(void)showActionSheetWithTwoActionTitle:(NSString *)title message:(NSString *)message inViewController:(UIViewController *)viewcontroller actionClicked:(ActionClicked)oneActionClicked actionClicked:(ActionClicked)twoActionClicked  titles:(NSArray *)strArray buts:(UIButton *)buts{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *oneAction = [UIAlertAction actionWithTitle:strArray[0] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        oneActionClicked();
    }];
    UIAlertAction *twoAction = [UIAlertAction actionWithTitle:strArray[1] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        twoActionClicked();
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:oneAction];
    [alert addAction:twoAction];
    [alert addAction:cancelAction];
    UIPopoverPresentationController *popPresenter = [alert popoverPresentationController];
    popPresenter.sourceView = buts; // 这就是挂靠的对象
    popPresenter.sourceRect = buts.bounds;
    [viewcontroller presentViewController:alert animated:YES completion:nil];
  
}
+(void)showActionSheetWithTwoActionTitle:(NSString *)title message:(NSString *)message inViewController:(UIViewController *)viewcontroller actionClicked:(ActionClicked)oneActionClicked   titles:(NSArray *)strArray{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *oneAction = [UIAlertAction actionWithTitle:strArray[0] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        oneActionClicked();
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
        alert.popoverPresentationController.sourceRect=CGRectMake(0, 0, kScreenWidth, kScreenHeight-200);
        alert.popoverPresentationController.sourceView=viewcontroller.view;
    [alert addAction:oneAction];
    [alert addAction:cancelAction];
    
    [viewcontroller presentViewController:alert animated:YES completion:^{
    }];
}
+(void)showActionSheetWithSXWActionTitle:(NSString *)title message:(NSString *)message inViewController:(UIViewController *)viewcontroller actionClicked:(ActionClicked)oneActionClicked   titles:(NSArray *)strArray but:(UIButton *)buts{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *oneAction = [UIAlertAction actionWithTitle:strArray[0] style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        oneActionClicked();
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:oneAction];
    
    [alert addAction:cancelAction];
    UIPopoverPresentationController *popPresenter = [alert popoverPresentationController];
    popPresenter.sourceView = buts; // 这就是挂靠的对象
    popPresenter.sourceRect = buts.bounds;
    [viewcontroller presentViewController:alert animated:YES completion:nil];
}
+(void)show2AlertTitle:(NSString *)title message:(NSString *)message invc:(UIViewController *)vc cancel:(ActionClicked)cancel detemin:(ActionClicked)detemin but:(UIButton *)but{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *oneAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        cancel();
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        detemin();
    }];
    [alert addAction:oneAction];
    [alert addAction:cancelAction];
    UIPopoverPresentationController *popPresenter = [alert popoverPresentationController];
    popPresenter.sourceView = but; // 这就是挂靠的对象
    popPresenter.sourceRect = but.bounds;
    [vc presentViewController:alert animated:YES completion:nil];
}
+(void)show2AlertMessage:(NSString *)message invc:(UIViewController *)vc cancel:(ActionClicked)cancel detemin:(ActionClicked)detemin but:(UIButton *)but{
    [self show2AlertTitle:nil message:message invc:vc cancel:cancel detemin:detemin but:but];
}

/**
 底部弹窗 除取消之外有两个选项
 @param strArray           选项标题数组
 */
-(void)showActionSheetWithThreeActionTitle:(NSString *)title message:(NSString *)message inViewController:(UIViewController *)viewcontroller actionClicked:(ActionClicked)oneActionClicked actionClicked:(ActionClicked)twoActionClicked actionClicked:(ActionClicked)threeActionClicked titles:(NSArray *)strArray{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *oneAction = [UIAlertAction actionWithTitle:strArray[0] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        oneActionClicked();
    }];
    UIAlertAction *twoAction = [UIAlertAction actionWithTitle:strArray[1] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        twoActionClicked();
    }];
    UIAlertAction *threeAction = [UIAlertAction actionWithTitle:strArray[2] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        threeActionClicked();
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:oneAction];
    [alert addAction:twoAction];
    [alert addAction:threeAction];
    [alert addAction:cancelAction];
    alert.popoverPresentationController.sourceRect=CGRectMake(0, 0, kScreenWidth, kScreenHeight-200);
    alert.popoverPresentationController.sourceView=viewcontroller.view;
    [viewcontroller presentViewController:alert animated:YES completion:^{
    }];
}



@end
